import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:photo_manager/photo_manager.dart';

class MediaGridItem extends StatefulWidget {
  final AssetEntity entity;
  final bool isSelected;
  final int? selectOrder;
  final bool isDisabled;
  final bool isVideo;
  final String? duration;
  final VoidCallback? onTap;

  const MediaGridItem({
    Key? key,
    required this.entity,
    this.isSelected = false,
    this.selectOrder,
    this.isDisabled = false,
    this.isVideo = false,
    this.duration,
    this.onTap,
  }) : super(key: key);

  @override
  State<MediaGridItem> createState() => _MediaGridItemState();
}

class _MediaGridItemState extends State<MediaGridItem> {
  static final Map<String, Uint8List> _thumbnailCache = {};
  Uint8List? _thumbData;
  bool _loading = false;
  bool _error = false;

  @override
  void initState() {
    super.initState();
    _loadThumb();
  }

  void _loadThumb() async {
    final key = "${widget.entity.id}_${ThumbnailSize(200, 200).toString()}";
    if (_thumbnailCache.containsKey(key)) {
      setState(() {
        _thumbData = _thumbnailCache[key];
      });
      return;
    }
    setState(() { _loading = true; _error = false; });
    try {
      final data = await widget.entity.thumbnailDataWithSize(ThumbnailSize(200, 200));
      if (data != null) {
        _thumbnailCache[key] = data;
      }
      if (mounted) {
        setState(() {
          _thumbData = data;
          _loading = false;
        });
      }
    } catch (e) {
      if (mounted) {
        setState(() { _error = true; _loading = false; });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    Widget thumbnail;
    if (_error) {
      thumbnail = Container(
        color: Colors.red,
        child: Center(child: Icon(Icons.error, color: Colors.white)),
      );
    } else if (_thumbData != null) {
      thumbnail = Image.memory(_thumbData!, fit: BoxFit.cover, width: double.infinity, height: double.infinity);
    } else {
      thumbnail = Container(color: Colors.grey[300]);
    }
    return RepaintBoundary(
      child: AspectRatio(
        aspectRatio: 1.0,
        child: GestureDetector(
          onTap: widget.onTap,
          child: Stack(
            children: [
              Positioned.fill(child: thumbnail),
              if (widget.isDisabled)
                Positioned.fill(
                  child: Container(color: Colors.black54),
                ),
              if (widget.isVideo && widget.duration != null)
                Positioned(
                  bottom: 4,
                  left: 4,
                  child: Container(
                    padding: EdgeInsets.symmetric(horizontal: 4, vertical: 2),
                    decoration: BoxDecoration(
                      color: Colors.black54,
                      borderRadius: BorderRadius.circular(4),
                    ),
                    child: Text(
                      widget.duration!,
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 10,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  ),
                ),
              if (widget.isSelected)
                Positioned(
                  top: 8,
                  right: 8,
                  child: Container(
                    width: 20,
                    height: 20,
                    decoration: BoxDecoration(
                      color: Colors.red,
                      shape: BoxShape.circle,
                    ),
                    child: Center(
                      child: Text(
                        '${widget.selectOrder}',
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 12,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                  ),
                ),
            ],
          ),
        ),
      ),
    );
  }
}
